package com.carrental.auth.filter;

import com.carrental.auth.config.JwtConfig;
import com.carrental.auth.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * JWT认证过滤器
 */
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final UserService userService;
    private final JwtConfig jwtConfig;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        log.debug("JWT过滤器开始执行: {}", request.getRequestURI());
        
        // 从请求头中获取token
        String authorizationHeader = request.getHeader("Authorization");
        
        // 如果请求头中没有Authorization信息，则直接放行
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            log.debug("请求头中没有Bearer token，直接放行");
            filterChain.doFilter(request, response);
            return;
        }
        
        // 提取token
        String token = authorizationHeader.substring(7);
        log.debug("从请求头中提取到token: {}", token);
        
        try {
            // 首先检查Redis中是否存在该token
            Object redisUserId = redisTemplate.opsForValue().get("token:" + token);
            if (redisUserId == null) {
                log.warn("Redis中不存在该token，可能已过期或被注销");
                SecurityContextHolder.clearContext();
                filterChain.doFilter(request, response);
                return;
            }
            
            // 验证token并获取用户ID
            Long userId = userService.getUserIdFromToken(token);
            
            // 验证token中的用户ID与Redis中存储的是否一致
            if (userId != null && userId.equals(Long.valueOf(redisUserId.toString()))) {
                log.debug("token有效，用户ID: {}", userId);
                
                // 获取用户角色
                List<String> roles = userService.getRolesByUserId(userId);
                log.debug("用户角色: {}", roles);
                
                // 将角色转换为SimpleGrantedAuthority
                List<SimpleGrantedAuthority> authorities = roles.stream()
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                        .collect(Collectors.toList());
                
                // 创建认证信息
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userId, null, authorities);
                
                // 将认证信息放入SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
                log.debug("已将认证信息放入SecurityContext");
            } else {
                log.warn("token无效或与Redis中存储的用户ID不匹配");
                SecurityContextHolder.clearContext();
            }
        } catch (Exception e) {
            // 如果token验证失败，清空SecurityContext
            log.error("处理token时发生异常: {}", e.getMessage());
            SecurityContextHolder.clearContext();
        }
        
        // 继续过滤器链
        log.debug("JWT过滤器执行完毕，继续过滤器链");
        filterChain.doFilter(request, response);
    }
} 